$(document).ready(function(){

    $('.user_status').each(function(){
            $(this).bootstrapSwitch('state', parseInt($(this).val()), true);
            $(this).on('switchChange.bootstrapSwitch', function(event, state) {
                userStatusSwitch($(this).data('userid'), state);
            });
        });
    $('#status_new').bootstrapSwitch('state', true, true);
    
    $('.usereditbtn').bind('click', function(){

        var userid = $(this).data('userid');

        inlineEdit(userid);
        $(this).addClass('hide');
        $('#userdeletebtn_' + userid).addClass('hide');
        $('#usersavebtn_' + userid).removeClass('hide');
        $('#usercancelbtn_' + userid).removeClass('hide');
    });

    $('.changepwdbtn').bind('click', function(){

        var userId = $(this).data('userid');

        resetPwdPop(userId);
    });

    $('.resetPwdPopClose').bind('click', function(){
        closeResetPwdPop()
    });

    $('#resetPopSave').bind('click', function(){
        var userId = $(this).data('userid');
        var newPwd = $('#resetPopPwd').val();
        if(newPwd == '' || newPwd.length<8)
        {
            alert('Are you kidding me?');
        }
        else
        {
            $.ajax({
                url: _USERUPDATEURL_,
                data: {
                    aid: userId,
                    pwd: newPwd
                },
                type: 'POST',
                success: function(rstdata){
                    closeResetPwdPop();
                    $('#userid_' + userId).addClass("alert alert-success");
                }
            });
        }
        $('#resetPopPwd').val('');
    })

    $('.userdeletebtn').bind('click', function(){

        var userid = $(this).data('userid');

        inlineDelete(userid);
    });

    $('.usersavebtn').bind('click', function(){

        var userid = $(this).data('userid');

        inlineSave(userid);

        $(this).addClass('hide');
        $('#usercancelbtn_' + userid).addClass('hide');
        $('#usercancelbtn_' + userid).removeClass('hide');
        $('#userdeletebtn_' + userid).removeClass('hide');
    });

    $('.usercancelbtn').bind('click', function(){

        var userid = $(this).data('userid');

        cancelInlineEdit(userid);

        $(this).addClass('hide');
        $('#usersavebtn_' + userid).addClass('hide');
        $('#usereditbtn_' + userid).removeClass('hide');
        $('#userdeletebtn_' + userid).removeClass('hide');
    });

    $('.useraddbtn').bind('click', function(){
        inlineAdd();
    })

    $('#tb').bind('mousewheel', function(event, delta) {  
        theadWidth();
        $('.t_h').css('border-bottom-color',randomcolor());
    });

    theadWidth();

});


function inlineEdit(userid) {

    var nickname = $('#nickname_' + userid).html();
    var email = $('#email_' + userid).html();
    var role_id = $('#role_id_' + userid).val();
    var status = $('#status_' + userid).find('input');
    var remark = $('#remark_' + userid).html();

    var selected_0 = role_id==0?'selected':'';
    var selected_1 = role_id==1?'selected':'';
    var selected_2 = role_id==2?'selected':'';
    var selected_3 = role_id==3?'selected':'';
    var selected_4 = role_id==4?'selected':'';
    var selected_5 = role_id==5?'selected':'';

    $('#nickname_' + userid).html('<textarea name="nickname" type="text" style="width:80px;" id="inputNickname_' + userid + '">' + nickname + '</textarea>');
    $('#email_' + userid).html('<textarea name="email" type="text" class="col-lg-12" id="inputEmail_' + userid + '">' + email + '</textarea>');
    $('#role_' + userid).html(
            '<select name="role" id="inputRole_' + userid + '" class="form-control">' +
                '<option value="0" ' + selected_0 + '>超级无敌管理员</option>' +
                '<option value="1" ' + selected_1 + '>无敌管理员</option>' +
                '<option value="2" ' + selected_2 + '>超级管理员</option>' +
                '<option value="3" ' + selected_3 + '>管理员</option>' +
                '<option value="4" ' + selected_4 + '>屌丝管理员</option>' +
                '<option value="5" ' + selected_5 + '>不是管理员</option>' +
            '</select>'
        );

    $('#group_' + userid).html(
            '<select name="group" id="inputGroup_' + userid + '" class="form-control">' +
            '<option value="' + $('#group_id_' + userid).val() + '">' + $('#group_name_' + userid).html() + '</option>' +
            $('#group_new').html() +
            '</select>'
        );

//    $('#status_' + userid).html('<input type="checkbox" class="form-control" id="inputStatus_' + userid + '" checked disabled />');    
    var status_switch = '';
    if(status.val() != 0){
        status_switch = "bootstrap-switch-on";
    }else{
        status_switch = "bootstrap-switch-off";
    }

    var stat = '<div class="bootstrap-switch bootstrap-switch-wrapper '
                + status_switch
                + ' bootstrap-switch-id-user_status_'
                + userid
                + ' bootstrap-switch-animate">'
                + '<div class="bootstrap-switch-container">'
                + '<span class="bootstrap-switch-handle-on bootstrap-switch-primary">ON</span>'
                + '<label class="bootstrap-switch-label">&nbsp;</label>'
                + '<span class="bootstrap-switch-handle-off bootstrap-switch-default">OFF</span>'
                + '<input type="checkbox" class="user_status" value="'
                + status.val()
                + '" id="user_status_'
                + userid
                + '" data-userid="'
                + userid
                + '" checked=""></div></div>';
    $('#status_' + userid).html(stat);
    $('#remark_' + userid).html('<textarea name="remark" type="text" class="col-lg-12" id="inputRemark_' + userid + '">' + remark + '</textarea>');
    
}

function cancelInlineEdit(userid) {

    var nickname = $('#inputNickname_' + userid).val();
    var email = $('#inputEmail_' + userid).val();
    var role = $('#inputRole_' + userid).val();
    var group = $('#inputGroup_' + userid).val();
    var status = $('#status_' + userid).find('input');
    //var status = $('#inputStatus_' + userid).val();
    var remark = $('#inputRemark_' + userid).val();

    var status_switch = '';
    if(status.val() != 0){
        status_switch = "bootstrap-switch-on";
    }else{
        status_switch = "bootstrap-switch-off";
    }
    
    var stat = '<div class="bootstrap-switch bootstrap-switch-wrapper '
                + status_switch
                + ' bootstrap-switch-id-user_status_'
                + userid
                + ' bootstrap-switch-animate">'
                + '<div class="bootstrap-switch-container">'
                + '<span class="bootstrap-switch-handle-on bootstrap-switch-primary">ON</span>'
                + '<label class="bootstrap-switch-label">&nbsp;</label>'
                + '<span class="bootstrap-switch-handle-off bootstrap-switch-default">OFF</span>'
                + '<input type="checkbox" class="user_status" value="'
                + status.val()
                + '" id="user_status_'
                + userid
                + '" data-userid="'
                + userid
                + '" checked=""></div></div>';
    
    $('#nickname_' + userid).html(nickname);
    $('#email_' + userid).html(email);
    $('#role_' + userid).html('<input type="hidden" id="role_id_' + userid + '" value="' + role + '">' + USERROLE[role]);
    $('#group_' + userid).html('<input type="hidden" id="group_id_' + userid + '" value="' + group + '">' + group);
    $('#status_' + userid).html(stat);
    $('#remark_' + userid).html(remark);
}


function inlineSave(userid) {

    var nickname = $('#inputNickname_' + userid).val();
    var email = $('#inputEmail_' + userid).val();
    var role = $('#inputRole_' + userid).val();
    var group = $('#inputGroup_' + userid).val();
    //var status = $('#inputStatus_' + userid).val();
    var remark = $('#inputRemark_' + userid).val();
    

    $.ajax({
        url: _USERUPDATEURL_,
        data: {
            aid: userid,
            nickname: nickname,
            email: email,
            role: role,
            group: group,
            //status: status,
            remark: remark
        },
        type: 'POST',
        success: function(rstdata){
            cancelInlineEdit(userid);
            $('#userid_' + userid).addClass("alert alert-success");
        }
    });
}

function inlineAdd() {
    var nickname = $('#nickname_new').val();
    var email = $('#email_new').val();
    var role = $('#role_new').val();
    var group = $('#group_new').val();
    var status = ($('#status_new').is(':checked'))?1:0;
    var remark = $('#remark_new').val();
    var password = $('#password_new').val();

    var alert_message = '';

    if(nickname.length == 0)
    {
        var alert_n = '<div class="alert alert-danger fade in">' +
                            '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                            'Nickname required!' +
                        '</div>';
        $('#nickname_new').after(alert_n);
    }
    if(email.length == 0)
    {
        var alert_e = '<div class="alert alert-danger fade in">' +
                            '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                            'Email required!' +
                        '</div>';
        $('#email_new').after(alert_e);
    }
    if(password.length == 0)
    {
        var alert_p = '<div class="alert alert-danger fade in">' +
                            '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                            'Password required!' +
                        '</div>';
        $('#password_new').after(alert_p);
    }

    if(nickname.length && email.length && password.length){

        $.ajax({
            url: _USERADDURL_,
            data: {
                nickname: nickname,
                email: email,
                role: role,
                group: group,
                status: status,
                remark: remark,
                pwd: password
            },
            type: 'POST',
            success: function(rstdata){
                var html = '<tr class="alert alert-success" id="userid_' + rstdata.aid + '">' +
                            '<td class="aid" id="aid_' + rstdata.aid + '">' + rstdata.aid + '</td>' +
                            '<td class="nickname" id="nickname_' + rstdata.aid + '">' + rstdata.nickname + '</td>' +
                            '<td class="email" id="email_' + rstdata.aid + '">' + rstdata.email + '</td>' +
                            '<td class="role" id="role_' + rstdata.aid + '">' + USERROLE[rstdata.role] + '</td>' +
                            '<td class="group" id="group_' + rstdata.aid + '">' + rstdata.group + '</td>' +
                            '<td class="status" id="status_' + rstdata.aid + '">' +
                            '<input type="checkbox" class="user_status" value="' + rstdata.status + '" id="user_status_' + rstdata.aid + '" data-userid="' + rstdata.aid + '" checked />' +
                            '</td>' +
                            '<td class="remark" id="remark_' + rstdata.aid + '">' + rstdata.remark + '</td>' +
                            '<td class="time">' + rstdata.time + '</td>' +
                            '<td>' +
                                '<a id="usereditbtn_' + rstdata.aid + '" data-userid="' + rstdata.aid + '" class="usereditbtn" style="font-size: 30px; color: #000;" href="javascript:void(0)"><span class="glyphicon glyphicon-edit" title="Edit"></span></a>' +
                                '<a id="userdeletebtn_' + rstdata.aid + '" class="userdeletebtn" data-userid="' + rstdata.aid + '" style="font-size: 30px; color: #000;" href="javascript:void(0)"><span class="glyphicon glyphicon-floppy-remove" title="Trash"></span></a>' +
                                '<a id="usersavebtn_' + rstdata.aid + '" data-userid="' + rstdata.aid + '" class="usersavebtn hide" style="font-size: 30px; color: #000;" href="javascript:void(0)"><span class="glyphicon glyphicon-floppy-saved" title="Save"></span></a>' +
                                '<a id="usercancelbtn_' + rstdata.aid + '" data-userid="' + rstdata.aid + '" class="usercancelbtn hide" style="font-size: 30px; color: #000;" href="javascript:void(0)"><span class="glyphicon glyphicon-paperclip" title="Cancel"></span></a>' +
                            '</td>' +
                        '</tr>';

                
                $('#userend').before(html);
                $('#user_status_' + rstdata.aid).bootstrapSwitch('state', parseInt(rstdata.status), true);

                $('#nickname_new').val('');
                $('#email_new').val('');
                
                $('#status_new').bootstrapSwitch('state', true, true);
                $('#remark_new').val('');
                $('#password_new').val('');
            }
        });
    }
}

function userStatusSwitch(uid, state){
    var status = state?1:0;
    $.ajax({
        url: _USERSTATUSURL_,
        data: {
            aid:uid,
            status:status
        },
        type: 'POST',
        success: function(rstdata){
            console.log(rstdata);
        }
    });
}

function inlineDelete(userid) {
    $.ajax({
        url: _DELETEURL_,
        data: {
            id: userid
        },
        type: 'POST',
        success: function(rstdata){
            $('#userid_' + userid).addClass('hide');
        }
    });
}

function inlineResume(userid) {
    $.ajax({
        url: _RESUMEURL_,
        data: {
            id: userid
        },
        type: 'POST',
        success: function(rstdata){
            $('#userid_' + userid).addClass('hide');
        }
    });
}

function theadWidth() {
    $('#h_id').width($('.id').width());
    $('#h_universe').width($('.universe').width());
    $('#h_company').width($('.company').width());
    $('#h_tsender').width($('.tsender').width());
    $('#h_tip').width($('.tip').width());
    $('#h_csender').width($('.csender').width());
    $('#h_cip').width($('.cip').width());
    $('#h_level').width($('.level').width());
    $('#h_isp').width($('.isp').width());

    if($('#h_operation')) {
        $('#h_operation').width($('.operation').width());
    }

}
function randomcolor(){
    var str=Math.ceil(Math.random()*16777215).toString(16);   
    if(str.length<6){   
        str="0"+str;   
    }
    return '#'+str;
}

function resetPwdPop(userId){
    $('#resetPwdPop').css({'top':$(window).scrollTop()+200});
    $('#resetPopEmail').val($('#inputEmail_'+userId).html());
    $('#resetPopSave').attr('data-userid', userId);
    $('#resetPwdPop').show();
    $('#overlay').show();
}

function closeResetPwdPop()
{
    $("#resetPwdPop").hide();
    $("#overlay").hide();
}